// 面向对象 / 面向过程

// 定义一个红绿灯类（构造函数）
function Light($box){
    //装红绿灯的容器
    this.box = document.querySelector($box)
    // 初始值
    this.index = 1;
}

// 初始化图片的方法
Light.prototype.init = function(){
    
    console.log('初始化图片');
    // 创建图片标签
    this.img = new Image();
    // 图片设置不可拖拽
    this.img.draggable = false;
    // debugger 在页面上自动加上断点
    // debugger;
    this.img.src = `./img/${this.index}.jpeg`
    let time1;
    time1 = setInterval(function(){
        this.index++;
    },100)
    
    // 添加到容器中
    this.box.appendChild(this.img);
    // 初始化完成之后绑定点击事件
    this.bindClick();
}

// 绑定点击事件
Light.prototype.bindClick = function(){
    this.img.addEventListener('click',()=>{
        // this.index++;
        this.index = (this.index % 3) + 1;
        // 判断图片是否超过 1-3
        // this.index > 3 && (this.index = 1);
        this.img.src = `./img/${this.index}.jpeg`
    })
}
console.log(Light.prototype);

//绑定自动轮播事件
Light.prototype.autoPlay = function(){
    let time1;
    // clearInterval(time1)
    time1 = setInterval(()=>{
        this.index = (this.index % 3) + 1;
        this.img.src = `./img/${this.index}.jpeg`
    },1000)
    
    this.img.addEventListener('mouseenter',()=>{
        clearInterval(time1)
    })
    this.img.addEventListener('mouseleave',()=>{
        time1 = setInterval(()=>{
            this.index = (this.index % 3) + 1;
            this.img.src = `./img/${this.index}.jpeg`
        },1000)
    })
}

// 绑定点击上下事件
Light.prototype.updownClick = function(){
    let flag = true
    let timer2;
    timer2 = setInterval(()=>{
        if(flag)this.index++;
        if(!flag)this.index--;
        if(this.index==3)flag=false
        if(this.index==1)flag=true
        this.img.src = `./img/${this.index}.jpeg`
    },1000)
    this.img.addEventListener('mouseenter',()=>{
        clearInterval(timer2)   
    })
    this.img.addEventListener('mouseleave',()=>{
        timer2 = setInterval(()=>{
            if(flag)this.index++;
            if(!flag)this.index--;
            if(this.index==3)flag=false
            if(this.index==1)flag=true
            this.img.src = `./img/${this.index}.jpeg`
        },1000)
    })
}